package com.zhaungjie.base.conduit;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class TypeR<T> {
    private static final long serialVersionUID=1L;

    private Boolean success;
    private Integer code;
    private String message;
    private T data;

    public static<V> V tryExtract(TypeR<V> typeR) {
        if (typeR != null && typeR.success ) {
            return typeR.data;
        }
        return null;
    }

    // 无法获取数据时抛出异常
    public static<V> V extract(TypeR<V> typeR) throws Exception {
        if (typeR != null && typeR.success ) {
            return typeR.data;
        } else {
            String message = (typeR != null)?typeR.message:"null";
            log.error("远程调用失败！原因：{}",message);
            throw new Exception("Failed to extract data："+message);
        }
    }



    /**
     * 检查是否请求成功
     * @param typeR
     * @return
     * @param <V>
     * @throws Exception
     */
    public static<V> boolean isFailed(TypeR<V> typeR) {
        return typeR == null || !typeR.success;
    }



    /**
     * 捕获看结果是否成功
     * @return
     * @throws Exception
     */
    // 无法获取数据时抛出异常
    public static void capture(TypeR typeR) throws Exception {
        if (typeR == null || !typeR.success ) {
            String message = (typeR != null)?typeR.message:"null";
            log.error("远程调用失败！原因：{}",message);
            throw new Exception("Failed to extract data："+message);
        }
    }


    public T extract() throws Exception {
        return extract(this);
    }
    public T tryExtract()  {
        return tryExtract(this);
    }



}
